package com.kfh.ybracelet.chat;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.kfh.ybracelet.R;
import com.kfh.ybracelet.base.BaseActivity;
import com.kfh.ybracelet.bean.MessageBean;
import com.kfh.ybracelet.db.DatabaseManager;
import com.kfh.ybracelet.utils.Constant;

import java.util.LinkedHashSet;
import java.util.Set;

import de.greenrobot.event.EventBus;

/**
 * 个人聊天设置页面
 * Created by Aaron on 16/3/11.
 */
public class ChatSettingActivity extends BaseActivity {

    private android.widget.ImageView ivpic;
    private android.widget.TextView tvnickname;
    private android.widget.TextView tvtel;
    private android.widget.ImageView ivremaind;
    private android.widget.RelativeLayout rlclear;
    private MessageBean contact;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_chat_setting);

        contact = getIntent().getParcelableExtra("contact");
        
        initWidget();

        fullData();

    }

    /**
     * 填充数据
     */
    private void fullData() {

        if (contact == null)
            return;

        tvnickname.setText(contact.receiveName);
        tvtel.setText(contact.receiveId);
        Glide.with(this)
                .load(contact.receivePic)
                .dontAnimate().diskCacheStrategy(DiskCacheStrategy.SOURCE).fitCenter()
                .placeholder(R.mipmap.temp_pic)
                .into(ivpic);

        Set<String> remadinSet = sp.getStringSet(Constant.REMAIND + sp.getString(Constant.USERID, ""), null);

        ivremaind.setSelected(!(remadinSet != null && remadinSet.contains(contact.channelId)));

    }

    private void initWidget() {

        this.rlclear = (RelativeLayout) findViewById(R.id.rl_clear);
        this.ivremaind = (ImageView) findViewById(R.id.iv_remaind);
        this.tvtel = (TextView) findViewById(R.id.tv_tel);
        this.tvnickname = (TextView) findViewById(R.id.tv_nickname);
        this.ivpic = (ImageView) findViewById(R.id.iv_pic);

        ImageView iv_left = (ImageView) findViewById(R.id.iv_left);
        TextView tv_title = (TextView) findViewById(R.id.tv_title);

        tv_title.setText(getResources().getString(R.string.setting));

        iv_left.setOnClickListener(this);
        rlclear.setOnClickListener(this);
        ivremaind.setOnClickListener(this);

    }

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {

            case R.id.iv_left:
                finish();
                break;

            case R.id.iv_remaind://消息提醒

                if (ivremaind.isSelected())
                    setRemaind(false);
                else
                    setRemaind(true);

                ivremaind.setSelected(!ivremaind.isSelected());

                break;

            case R.id.rl_clear://清除聊天记录

                if (contact == null)
                    return;

                new AlertDialog.Builder(this).setTitle("提醒").setMessage("清空聊天记录,该操作不可恢复").setNegativeButton("取消", null)
                        .setPositiveButton("清空", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                new DeleteTask().execute();
                            }
                        }).show();

                break;

        }

    }

    /**
     * 删除聊天记录的task
     */
    private class DeleteTask extends AsyncTask<String, String, String> {

        private ProgressDialog show;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            show = ProgressDialog.show(ChatSettingActivity.this, "请稍后", "正在删除聊天记录");
        }

        @Override
        protected String doInBackground(String... params) {


            DatabaseManager.getInstance().deleteHistory(ChatSettingActivity.this, contact.channelId, sp.getString(Constant.USERID, ""));
            DatabaseManager.getInstance().clearTopic(ChatSettingActivity.this, new String[]{
                    //db.execSQL("update " + Constant.TOPIC_TABLE + " set sendId=?,content=?" +
//                    ",messageType=?,chatType=?,sendTime=?,receivePic=?, receiveName=?,receiveId=? where topic=? and userId=?", args);
                    sp.getString(Constant.USERID, ""), "", Constant.MQTTMESSAGETEXT, "",
                    contact.receivePic, contact.receiveName, contact.receiveId, contact.channelId, sp.getString(Constant.USERID, "")

            });

            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            if (show != null && show.isShowing())
                show.dismiss();

            contact.operationStyle = Constant.DELETE_RECENT_HISTORY;
            contact.messageType = Constant.MQTTMESSAGETEXT;
//            contact.chatType = Constant.CHAT_SINGLE;
            contact.content = "";
            EventBus.getDefault().post(contact);

            showToast("删除成功");

        }

    }


    /**
     * 新消息是否提醒
     *
     * @param remaind
     */
    private void setRemaind(boolean remaind) {

        if (contact == null)
            return;

        SharedPreferences.Editor edit = sp.edit();

        Set<String> remaindSet = sp.getStringSet(Constant.REMAIND + sp.getString(Constant.USERID, ""), new LinkedHashSet<String>());

        if (remaind)
            remaindSet.remove(contact.channelId);
        else
            remaindSet.add(contact.channelId);

        edit.putStringSet(Constant.REMAIND + sp.getString(Constant.USERID, ""), remaindSet).apply();

    }

}
